'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  const {
    taskId,
    content,
    type = 'text',
    receiverId: clientReceiverId, 
    title = '',
    status = 'pending' 
  } = event;

  if (!event.uniIdToken) {
    console.error('[sendChatMessage] Invocation failed, uniIdToken is missing.');
    return {
      code: 401,
      errCode: 'uni-id-token-required',
      msg: 'User not logged in or token is invalid'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  if (!content) {
    return { code: 400, msg: 'Missing content' };
  }
  
  // 对于纯私信聊天，taskId是可选的
  if (!taskId && !clientReceiverId) {
    return { code: 400, msg: 'Missing taskId or receiverId' };
  }

  try {
    const { uid: senderId } = await uniIDIns.checkToken(event.uniIdToken);
    if (!senderId) {
      return { code: 401, msg: 'User not logged in' };
    }

    const user = await db.collection('uni-id-users').doc(senderId).field({
      _id: 1,
      nickname: 1,
      'avatar_file.url': 1
    }).get();
    
    if (!user.data || user.data.length === 0) {
        return { code: 404, msg: 'Sender user does not exist' };
    }
    const senderInfo = user.data[0];
    const senderAvatar = (senderInfo.avatar_file && senderInfo.avatar_file.url) ? senderInfo.avatar_file.url : '/static/images/default-avatar.png';


    let receiverId;
    if (clientReceiverId) {
        receiverId = clientReceiverId;
        console.log('[sendChatMessage] 使用客户端传递的receiverId:', receiverId);
    } else {
        console.log('[sendChatMessage] 查询任务信息, taskId:', taskId);
        // 查询任务信息，支持多种字段名
        const task = await db.collection('taskList').doc(taskId).field({ 
          publisher_id: 1, 
          receiver_id: 1,
          userId: 1 
        }).get();
        
        console.log('[sendChatMessage] 任务查询结果:', task.data);
        
        if (!task.data || task.data.length === 0) {
            console.log('[sendChatMessage] 任务不存在, taskId:', taskId);
            return { code: 404, msg: 'Associated task does not exist' };
        }
        
        const taskData = task.data[0];
        // 优先使用 publisher_id，如果没有则使用 userId
        receiverId = taskData.publisher_id || taskData.userId;
        console.log('[sendChatMessage] 从任务获取的receiverId:', receiverId);
    }

    if (senderId === receiverId) {
        return { code: 200, msg: 'Message sent (no actual operation)' }; 
    }

    const messageData = {
      taskId,
      type,
      senderId,
      senderAvatar: senderAvatar,
      senderNickname: senderInfo.nickname || '用户',
      content,
      createTime: new Date().toISOString(),
      status: 'unread',
      receiverId
    };

    if (type === 'card') {
      messageData.title = title;
      messageData.status = status;
    }
    
    // 添加图片消息支持
    if (type === 'image' && event.imageUrl) {
      messageData.imageUrl = event.imageUrl;
    }
    
    // 添加位置消息支持
    if (type === 'location' && event.location) {
      messageData.location = event.location;
    }

    const result = await db.collection('chatMessages').add(messageData);

    return {
      code: 200,
      msg: 'Message sent successfully',
      data: {
        _id: result.id,
        ...messageData
      }
    };

  } catch (error) {
    console.error('Failed to send message:', error);
    if (error.code && error.code.startsWith('uni-id-')) {
        return { errCode: error.code, msg: error.message };
    }
    return {
      code: 500,
      msg: 'Server internal error',
      error: error.message
    };
  }
}; 